package cn.tsmchina.one.controller.category;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import cn.tsmchina.one.domain.category.Category;
import cn.tsmchina.one.domain.product.Product;
import cn.tsmchina.one.domain.user.Customer;
import cn.tsmchina.one.pojo.RestaurantPojo;
import cn.tsmchina.one.service.category.CategoryService;
import cn.tsmchina.one.service.product.ProductService;
import cn.tsmchina.one.service.user.CustomerService;
import cn.tsmchina.one.util.C;
import cn.tsmchina.one.util.JsonUtil;
import cn.tsmchina.one.util.LoginUtil;
import cn.tsmchina.one.util.MD5Util;
import cn.tsmchina.one.util.Return;

@Controller
@RequestMapping("/categorym")
public class CategoryMController
{
	@Autowired
	private CategoryService categoryService;
	
	@Autowired
	private ProductService productService;
	@Autowired
	private CustomerService customerService;
	@RequestMapping("/add")
	public String add()
	{
		return "category/addCategory";
	}
	
	/**
	 * 添加活动信息提交
	 * @param activity
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/add",method= RequestMethod.POST)
	public String addActivity(@ModelAttribute RestaurantPojo category,HttpServletRequest request)
	{
		try
		{	
			Map<String, Object> paramsMap = new HashMap<>();
			paramsMap.put("phone", category.getPhone());
			paramsMap.put("address", category.getAddress());
			paramsMap.put("name", category.getName());
			paramsMap.put("images", category.getImages());
			paramsMap.put("nav", category.getNav());
			String params = JsonUtil.parseJson(paramsMap);
			long cid = LoginUtil.getCustomerId(request, customerService);
			String genId = categoryService.genId(null, cid);
			
			Customer toSaveCus = new Customer();
			Category toSave = new Category();
			String nPwd = MD5Util.encodeByMD5(category.getLoginPwd());
			toSave.setCid(genId);
			toSave.setName(category.getName());
			toSave.setLoginId(category.getLoginId());
			toSaveCus.setLoginId(category.getLoginId());
			toSave.setLoginPwd(nPwd);
			toSaveCus.setLoginPwd(nPwd);
			toSave.setUname(category.getUname());
			toSaveCus.setName(category.getUname());
			toSave.setParams(params);
			toSave.setCustomerId(cid);
			//检查登陆ID是否存在，如果存在则不能添加
			Category check = categoryService.getByCategoryLoginId(category.getLoginId());
			Customer checkc = customerService.getCustomerByLoginId(category.getLoginId());
			int total = customerService.getAllCustomers().size();
			if(total >= 11)
			{
				request.setAttribute("msgType", C.Msg.ERROR);
				request.setAttribute("msg", "添加失败，店铺数量达到上限(overflow)!");
				request.setAttribute("return",request.getContextPath()+"/categorym/query");
			}
			else if(null != check && null != checkc)
			{
				request.setAttribute("msgType", C.Msg.ERROR);
				request.setAttribute("msg", "添加失败，登陆ID已经存在(the loginId is exited)!");
				request.setAttribute("return",request.getContextPath()+"/categorym/query");
			}
			
			else
			{
				//同步更新customer表
				categoryService.addCategory(toSave);
				customerService.addCustomer(toSaveCus);
				request.setAttribute("msgType", C.Msg.OK);
				request.setAttribute("msg", "添加成功!");
				request.setAttribute("return",request.getContextPath()+"/categorym/query");
			}
		} catch (Exception e)
		{
			request.setAttribute("msgType", C.Msg.ERROR);
			request.setAttribute("msg", "添加失败!");
			request.setAttribute("return",request.getContextPath()+"/categorym/query");
		}
		
		return Return.redirect(request);
	}
	
	@RequestMapping("/editSubCategory/{id}")
	public String editSubCategory(@PathVariable("id") int id, Model model,HttpServletRequest request)
	{
		long cid = LoginUtil.getCustomerId(request, customerService);
		List<Category> categories = categoryService.getAllSubRestaurant(cid);
		model.addAttribute("categories", categories);
		String categoryId = categoryService.getById(id).getCid();
		List<Category> foods = categoryService.getAllFoodCategory(categoryId, cid);//对于本应用，每个店铺的菜品种类肯定是一致的，故为了后台在添加菜品时避免二级目录联动，这里做简化处理
		model.addAttribute("foods", foods);
		model.addAttribute("pid", id);
		
		return "category/editSubCategory";
	}
	
	@RequestMapping(value="/submitEditSubCategory", method=RequestMethod.POST)
	public String editSubCategory(String oldParams, String[] newest, int pid, Model model,HttpServletRequest request)
	{
		try {
			long cid = LoginUtil.getCustomerId(request, customerService);
			String pidStr = categoryService.getById(pid).getCid();
			
			List<Category> subCategories =categoryService.getAllFoodCategory(pidStr, cid);
			Map<Integer, String> idNameMap = new HashMap<>();
			for (Category tmpCategory : subCategories) {
				idNameMap.put(tmpCategory.getId(), tmpCategory.getName());
			}
			//update
			if(!oldParams.isEmpty()) {
				for (String string : oldParams.split(";")) {
					int id = Integer.parseInt(string.split("____")[0]);
					if(idNameMap.containsKey(id)) {
						String name = string.split("____")[1];
						if(!idNameMap.get(id).equals(name)) {
							Category toUpdate = categoryService.getById(id);
							toUpdate.setName(name);
							categoryService.updateCategory(toUpdate);
						}
					}
				}
			}
			
			
			//delete
			if(!oldParams.isEmpty()) {
				Set<Integer> nowIds = new HashSet<>();
				for (String s : oldParams.split(";")) {
					int id = Integer.parseInt(s.split("____")[0]);
					nowIds.add(id);
				}
				for (Integer key : idNameMap.keySet()) {
					if(!nowIds.contains(key)) {
						//delete
						categoryService.deleteCategory(key);
					}
				}
			}
			
			//add
			if(newest!=null) {
				for (String string : newest) {
					Category newCategory = new Category();
					newCategory.setName(string);
					String categoryCid = categoryService.genId(pidStr, cid);
					newCategory.setCid(categoryCid);
					newCategory.setCustomerId(cid);
					categoryService.addCategory(newCategory);
				}
			}
			
			request.setAttribute("msgType", C.Msg.OK);
			request.setAttribute("msg", "编辑成功!");
			request.setAttribute("return",request.getContextPath()+"/categorym/editSubCategory/"+pid);
		} catch(Exception e) {
			request.setAttribute("msgType", C.Msg.ERROR);
			request.setAttribute("msg", "编辑失败!");
			request.setAttribute("return",request.getContextPath()+"/categorym/editSubCategory/"+pid);
		}
		return Return.redirect(request);
	}

	@RequestMapping("/query")
	public String activity(Model model,HttpServletRequest request)
	{
		int page = 1;
		String curPage = request.getParameter("page");
		if(!StringUtils.isEmpty(curPage)){
			page = Integer.valueOf(curPage);
		}
		try
		{
			page = page <= 0 ? 1 : page;
			long cid = LoginUtil.getCustomerId(request, customerService);
			List<Category> list = categoryService.getSubRestaurant(page, cid);
			int total = categoryService.getAllSubRestaurant(cid).size();
			int pageTotal = total % C.Paging.SIZE == 0 ? total / C.Paging.SIZE : total / C.Paging.SIZE + 1;
			
			List<RestaurantPojo> restaurants = new ArrayList<>();
			for (Category category : list) {
				RestaurantPojo restaurantPojo = JsonUtil.parseObject(RestaurantPojo.class, category.getParams());
				restaurantPojo.setCid(category.getCid());
				restaurantPojo.setId(category.getId());
				restaurantPojo.setLoginId(category.getLoginId());
				restaurantPojo.setLoginPwd(category.getLoginPwd());
				restaurantPojo.setUname(category.getUname());

				restaurants.add(restaurantPojo);
			}
			model.addAttribute("total", total);
			model.addAttribute("pageTotal", pageTotal);
			model.addAttribute("page",page);
			model.addAttribute("categories", restaurants);
			model.addAttribute("len", list.size());
			
		} catch (Exception e)
		{
			model.addAttribute("len", 0);
		}
		
		return "category/queryCategory";
	}
	
	/**
	 * 店铺列表信息查询
	 * @param model
	 * @return
	 */
	@RequestMapping("/details/{id}")
	public String activity(@PathVariable("id") int id, Model model, HttpServletRequest request)
	{
		request.getSession().setAttribute("currentRestaurantId", id);//切换店铺的时候保存当前店铺的id
		Category restaurant = categoryService.getById(id);
//		request.setAttribute("restaurant", restaurant);
		restaurant(restaurant, model);
		return "m/restaurantDetails";
	}
	
	/**
	 * 店铺详情
	 * @param model
	 * @return
	 */
	@RequestMapping("/rquery/{id}")
	public String activityDetail(@PathVariable("id")int id,HttpServletRequest request)
	{
		return "activityDetail";
	}
	
	@InitBinder
	public void convertDate(WebDataBinder binder)
	{
		CustomDateEditor editor = new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"), false);
		binder.registerCustomEditor(Date.class,editor);
	}
	
	private void restaurant(Category restaurant, Model model)
	{
		RestaurantPojo restaurantPojo = JsonUtil.parseObject(RestaurantPojo.class, restaurant.getParams());
		restaurantPojo.setCid(restaurant.getCid());
		restaurantPojo.setId(restaurant.getId());
		model.addAttribute("restaurant", restaurantPojo);
	}
	
	/**
	 * 列出店铺指定菜品分类下的所有菜品
	 * @param id
	 * @param request
	 * @return
	 */
	@RequestMapping("/foods/{id}")
	public String listFoods(@PathVariable("id")int id, HttpServletRequest request)
	{
		int page = 1;
		String curPage = request.getParameter("page");
		if(!StringUtils.isEmpty(curPage)){
			page = Integer.valueOf(curPage);
		}
		long cid = LoginUtil.getCustomerId(request, customerService);
		String categoryCid = categoryService.getById(id).getCid();
		List<Category> categories = categoryService.getAllFoodCategory(categoryCid.substring(0, 4), cid);//4是第一层分类（子店铺）id的长度
		request.setAttribute("foodCategories", categories);
		request.setAttribute("id", id);
		List<Product> foods = productService.getFoodsByCategory(id, page);
		request.setAttribute("foods", foods);
		
		List<String> productsJson = new ArrayList<String>();
		for (Product product : foods) {
			Map<String, Object> data = new HashMap<>();
			data.put("id", product.getId());
			data.put("name", product.getProductName());
			data.put("price",product.getPrice());
			data.put("number", 1);
			data.put("images", product.getImages());
			productsJson.add(JsonUtil.parseJson(data));
		}
		
		int total = productService.getFoodsCountByCategory(id);
		if(total<=C.Paging.FRONT_PAGE_SIZE) {
			request.setAttribute("enablePage", false);
		} else {
			request.setAttribute("enablePage", true);
			if(page==1) {
				request.setAttribute("enableFirst", false);
			} else {
				request.setAttribute("enableFirst", true);
				request.setAttribute("prev", page-1);
			}
			
			int pageTotal = total % C.Paging.FRONT_PAGE_SIZE == 0 ? total / C.Paging.FRONT_PAGE_SIZE : total / C.Paging.FRONT_PAGE_SIZE + 1;
			if(page>=pageTotal) {
				request.setAttribute("enableLast", false);
			} else {
				request.setAttribute("enableLast", true);
				request.setAttribute("next", page+1);
			}
		}
		
		request.setAttribute("pjsons", productsJson);
		return "m/listFoods";
	}
	
	/**
	 * 修改活动信息
	 * @param id
	 * @return
	 */
	@RequestMapping("/edit/{id}")
	public String edit(@PathVariable("id") int id,HttpServletRequest request)
	{
		Category category = categoryService.getById(id);
		RestaurantPojo restaurantPojo = JsonUtil.parseObject(RestaurantPojo.class, category.getParams());
		restaurantPojo.setId(id);
		restaurantPojo.setLoginId(category.getLoginId());
		restaurantPojo.setLoginPwd(category.getLoginPwd());
		restaurantPojo.setUname(category.getUname());
		request.setAttribute("p", restaurantPojo);
		request.setAttribute("returnUrl",Return.encode(request.getHeader("referer")));
		return "category/editCategory";
	}
	
	/**
	 * 提交修改活动信息
	 * @param id
	 * @return
	 */
	@RequestMapping(value="/edit",method=RequestMethod.POST)
	public String edit(RestaurantPojo category,HttpServletRequest request)
	{
		try
		{
			Map<String, Object> paramsMap = new HashMap<>();
			paramsMap.put("phone", category.getPhone());
			paramsMap.put("address", category.getAddress());
			paramsMap.put("name", category.getName());
			paramsMap.put("images", category.getImages());
			paramsMap.put("nav", category.getNav());
			String params = JsonUtil.parseJson(paramsMap);
			
			Category toUpdate = categoryService.getById(category.getId());
			Customer toUpdateCus = customerService.getCustomerByLoginId(category.getLoginId());
			toUpdate.setName(category.getName());
			toUpdate.setLoginId(category.getLoginId());
			toUpdate.setLoginPwd(category.getLoginPwd());
			toUpdateCus.setLoginId(category.getLoginId());
			toUpdateCus.setLoginPwd(category.getLoginPwd());
			toUpdateCus.setName(category.getUname());
			toUpdate.setUname(category.getUname());
			toUpdate.setParams(params);
			
			
			categoryService.updateCategory(toUpdate);
			customerService.updateCustomer(toUpdateCus);
			request.setAttribute("msgType", C.Msg.OK);
			request.setAttribute("msg", "修改成功!");
			request.setAttribute("return",request.getParameter("return"));
		} catch (Exception e)
		{
			request.setAttribute("msgType", C.Msg.ERROR);
			request.setAttribute("msg", "修改失败!");
			request.setAttribute("return",request.getParameter("return"));
		}
		return Return.redirect(request);
	}
	
	@RequestMapping("/delete/{id}")
	public String delete(@PathVariable("id") int id,HttpServletRequest request)
	{
		try
		{
			Integer lid = categoryService.getById(id).getLoginId();
			categoryService.deleteCategory(id);
			Long cusId = customerService.getCustomerByLoginId(lid).getId();
			customerService.deleteCustomer(cusId);
			request.setAttribute("msgType", C.Msg.OK);
			request.setAttribute("msg", "删除成功!");
			request.setAttribute("return", request.getHeader("referer"));
		} catch (Exception e)
		{
			request.setAttribute("msgType", C.Msg.ERROR);
			request.setAttribute("msg", "删除失败!");
			request.setAttribute("return", request.getHeader("referer"));
		}
		return Return.redirect(request);
	}
}
